// pages/book-detail/book-detail.js

import {
  BookModel
} from '../../models/book.js'

import {
  LikeModel
} from '../../models/like.js'

let bookModel = new BookModel()
let likeModel = new LikeModel()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    book: null,
    starCount: 0,
    starStatus: false,
    posting: false,
    searching: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中'
    })
    const bookId = options.bookId
    const detail = bookModel.getDetail(bookId)
    const likeStatus = bookModel.getLikeStatus(bookId)
    const comments = bookModel.getComments(bookId)

    Promise.all([detail, likeStatus, comments]).then((res)=>{
      console.log(res)
      this.setData({
        book: res[0],
        starStatus: res[1].like_status,
        starCount: res[1].fav_nums,
        comments: res[2].comments
      })
      wx.hideLoading()
    })

    // detail.then(res => {
    //   console.log(res)
    //   this.setData({
    //     book: res
    //   })
    // })

    // comments.then(res => {
    //   console.log(res)
    //   this.setData({
    //     comments: res.comments
    //   })
    // })

    // likeStatus.then(res => {
    //   console.log(res)
    //   this.setData({
    //     starStatus: res.like_status,
    //     starCount: res.fav_nums
    //   })
    // })
  },

  onLike:function (event) {
    let behavior = event.detail.behavior
    likeModel.like(behavior,this.data.book.id, 400)
  },

  onFakePost: function () {
    /* 点击输入短评事件 ... */
    this.setData({
      posting: true
    })
  },

  onCancel: function (event) {
    /* 取消输入短评事件 ... */
    this.setData({
      posting: false
    })
  },

  getOnTag(event) {
    /* 点击已有标签+1 或者 用户自行输入 都触发此事件... 
    /* 通过detail.content获取组件点击传递的内容，
    通过detail.value获取input输入框中输入的内容 */
    const comment = event.detail.content || event.detail.value
    
    if (!comment) {return}

    if (comment.length > 12) {
      wx.showToast({
        title: '短评超过12个字，请修改一下吧',
        icon: 'none'
      })
      return
    }
    bookModel.postComments(this.data.book.id, comment)
      .then(res => {
        wx.showToast({
          title: '+ 1',
          icon: 'none'
        })
        this.data.comments.unshift({
          content: comment,
          nums: 1
        })
        this.setData({
          comments: this.data.comments,
          posting: false
        })
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})